﻿# importing required modules
import os,time,py7zr,shutil
# from ntpath import join

class folder_dir:
    '文件基类'
    # empCount = 0
    def _init_(self,new_name,root,old_path,m_time):
        self.new_name = ""
        self.root = ""
        self.old_path = ""
        self.m_time = 0   
    def oldcheck(self):
        if self.m_time > 0:
            return True


def get_all_folder(dir):
	folder_lis = []
	#list all producttype folder
	folder_T = os.listdir(dir)
	for folder_tt in folder_T:
		root_T = folder_tt
		path_T = os.path.join(dir,folder_tt)
		if os.path.isdir(path_T):
			folder_Y = os.listdir(path_T)
			for folder_yy in folder_Y:
				root_Y = root_T +'_'+folder_yy
				path_Y = os.path.join(path_T,folder_yy)
				if os.path.isdir(path_Y):
					folder_M = os.listdir(path_Y)
					for folder_mm in folder_M:
						root_M = root_Y +'_'+folder_mm
						path_M = os.path.join(path_Y,folder_mm)
						if os.path.isdir(path_M):
							folder_D = os.listdir(path_M)
							for folder_dd in folder_D:
								root_D = root_M +'_'+folder_dd
								path_D = os.path.join(path_M,folder_dd)
								if os.path.isdir(path_D):
									new_Path = os.path.join(path_Y,root_D)
									stinfo = os.stat(path_D)
									size = len(folder_lis)
									folder_lis.append(folder_dir())
									folder_lis[size].new_name = new_Path
									folder_lis[size].root = root_D
									folder_lis[size].old_path = path_D
									folder_lis[size].m_time = stinfo.st_mtime

	# print(file_paths)
	return folder_lis


def sevenzip(filename, zipname,roots):
    with py7zr.SevenZipFile(zipname, 'w') as z:
    	z.writeall(filename, arcname=roots)


def main():
	directory = 'C:\\AA_C2_Results'
	day_folder_List = get_all_folder(directory)
	#add a count to limit folder zipped in 1 time to five
	count = 0	
	for folder in day_folder_List:
		now = int(time.time())
		if (now-folder.m_time)>86400:#172800= 2 days
			# name with zip time
			newpath = folder.new_name + "-" +time.strftime("%y%m%d%H%M%S", time.localtime(int(time.time())))+".7z"
			# sevenzip(folder.old_path,folder.new_name+".7z",folder.root)
			sevenzip(folder.old_path,newpath,folder.root)
			print(folder.old_path+ "zipped!")
			count +=1
			# delete zipped file
			shutil.rmtree(folder.old_path)
			if count>4:
				break
	if count == 0:
		print("No file ready to zip!")
	else:
		print("All files zipped successfully!")

if __name__ == "__main__":
	main()




